import json
from typing import List, Callable

import midjourney_config
from global_config import *

from scripts.beans import Storyboard


def read_workflow(storyboards_path):
    with open(storyboards_path, 'r', encoding='utf-8') as file:
        storyboards: List[Storyboard] = [Storyboard(**json.loads(v)) for v in json.load(file)]
        # for v in storyboards:
        #     v.aiImgList = json.loads(v.aiImgList_temp)
        #     v.aiImgNameList = json.loads(v.aiImgNameList_temp)
    return storyboards


def save_wordflow(storyboards_path, storyboards):
    with open(storyboards_path, 'w', encoding='utf-8') as file:
        # for v in storyboards:
        #     v.aiImgList_temp = json.dumps(v.aiImgList)
        #     v.aiImgNameList_temp = json.dumps(v.aiImgNameList)
        file.write(json.dumps([json.dumps(v.__dict__, ensure_ascii=False) for v in storyboards], ensure_ascii=False))
        print('保存成功')


def save_config_json(config_json_path, suffix):
    with open(config_json_path, 'w', encoding='utf-8') as file:
        file.write(suffix)


def read_config_json(config_json_path):
    if not os.path.exists(config_json_path):
        return midjourney_config.global_shuff_style
    with open(config_json_path, 'r', encoding='utf-8') as file:
        return file.read()


def modify_workflow(storyboards_path, func: Callable = None):
    with open(storyboards_path, 'r+', encoding='utf-8') as file:
        storyboards: List[Storyboard] = [Storyboard(**json.loads(v)) for v in json.load(file)]
        if func is not None:
            func(storyboards)
        file.seek(0)
        file.flush()

        # for v in storyboards:
        #     v.aiImgList_temp = json.dumps(v.aiImgList)
        #     v.aiImgNameList_temp = json.dumps(v.aiImgNameList)
        file.write(json.dumps([json.dumps(v.__dict__, ensure_ascii=False) for v in storyboards], ensure_ascii=False))
        print('更新成功')


# 质量提示词配置
def save_project_config(data):
    with open(promot_config_path(), 'w', encoding='utf-8') as file:
        file.write(json.dumps(data, ensure_ascii=False))


def load_project_config():
    filepath = promot_config_path()
    if not os.path.exists(filepath):
        return midjourney_config.project_config
    with open(filepath, 'r') as file:
        data = json.load(file)
        if 'reasoning_platform' not in data:
            data['reasoning_platform'] = midjourney_config.gpt_platform_coze
            save_project_config(data)
        return data
